//
//  UIImageView+BOCNetworkImage.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "UIImageView+BOCNetworkImage.h"
#import "BOCNetworkImageManager.h"
#import "BOCImageDownloadTask.h"

@implementation UIImageView (BOCNetworkImage)

- (void)setNetworkImageWithURL:(NSURL *)url
{
    [self setNetworkImageWithURL:url placeholderImage:nil];
}

- (void)setNetworkImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage
{
    [self setNetworkImageWithURL:url placeholderImage:placeholderImage completion:nil];
}

- (void)setNetworkImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkImageWithURL:url placeholderImage:placeholderImage progress:nil completion:completionBlock];
}

- (void)setNetworkImageWithURL:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self setNetworkImageWithURL:url placeholderImage:nil progress:progressBlock completion:completionBlock];
}

- (void)setNetworkImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage progress:(BOCProgressHandlerProgressBlock)progressBlock completion:(DownloadCompletionBlock)completionBlock
{
    [self cancelDownlaodTask];
    if (placeholderImage) {
        dispatch_mainQueue_safely_sync(^{
            self.image = placeholderImage;
        });
    }
    BOCNetworkImageManager *manager = [BOCNetworkImageManager sharedManager];
    UIImage *cacheImage = [manager imageForURLkey:url];
    if (cacheImage) {
        dispatch_mainQueue_safely_sync(^{
            self.image = cacheImage;
            if (completionBlock) {
                completionBlock(cacheImage, nil, nil);
            }
        });
    } else {
        __weak typeof(self) weakSelf = self;
        BOCImageDownloadTask *task =
        [manager downImageWithURL:url
                         progress:progressBlock          
                          seccess:^(UIImage *image, NSURLResponse *response) {
                              
                              weakSelf.image = image;
                              if (completionBlock) {
                                  completionBlock(image,response,nil);
                              }
                          }                                                                                  fail:^(NSError *error, NSURLResponse *response) {
                              if (completionBlock) {
                                  completionBlock(nil,response,error);
                              }
                              
                          }];
            [self setDownloadTask:task forKey:objectKeyWithUrl(url)];
    }
}

- (void)cancelDownlaodTask
{
    dispatch_mainQueue_safely_sync(^{
        self.image = nil;
    });
    [super cancelAllDownlaodTask];
}

@end
